package ec.cd.client.profiler;

import java.net.Socket;
import java.util.logging.Logger;

import ec.cd.common.Sensors;

import android.app.Activity;
import android.hardware.SensorManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class EnergyProfilerHelperActivity extends Activity {
	/** Called when the activity is first created. */
	private SensorManager sensorManager;
	private int selectedSensor; // 1 for acc and 4 for gyro
	private boolean started = false;
	private int samplingRate; // 0-fastest, 1-Game, 2-UI, 3-Normal
	private SensorsManager sensorsManager;
	private Client client;
	private TextView clientLogsTextView;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.main);
		clientLogsTextView = (TextView) findViewById(R.id.textViewLog);

		sensorsManager = new SensorsManager(this, clientLogsTextView);

		RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
		Spinner spinnerSamplingRate = (Spinner) findViewById(R.id.spinnerSamplingRate);

		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
				this, R.array.sampling_rates,
				android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinnerSamplingRate.setAdapter(adapter);
		spinnerSamplingRate
				.setOnItemSelectedListener(new MyOnItemSelectedListener());
		Button button = (Button) findViewById(R.id.buttonStartStop);
		button.setOnClickListener(new MyOnClickListener());
	}

	private class ListenSensorsTask extends AsyncTask<Integer, Void, Void> {

		protected Void doInBackground(Integer... ints) {
			sensorsManager.startListening(ints[0], samplingRate);
			return null;
		}

	}

	private class ConnectTask extends AsyncTask<String, Void, Boolean> {
		protected void onPreExecute() {
		}

		// If not connected, ss must contain host and port
		protected Boolean doInBackground(String... ss) {
			if (ss[0].length() > 0 && ss[1].length() > 0) {
				try {
					client.connect(ss[0], Integer.parseInt(ss[1]));
					client.handleConnection();
				} catch (Exception ex) {
					Log.i("Error", ex.getStackTrace().toString());
				}
			}

			return false;
		}

		protected void onPostExecute(Boolean res) {
			// client.handleConnection();
		}
	}

	private class DisconnectTask extends AsyncTask<Void, Void, Void> {
		protected void onPreExecute() {

		}

		protected Void doInBackground(Void... objs) {
			client.disconnect();

			return null;
		}

		protected void onPostExecute(Void res) {

		}
	}

	private class MyOnItemSelectedListener implements OnItemSelectedListener {

		public void onItemSelected(AdapterView<?> parent, View view, int pos,
				long id) {
			samplingRate = pos;
		}

		public void onNothingSelected(AdapterView parent) {
			// Do nothing.
		}
	}

	private class MyOnClickListener implements OnClickListener {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			EditText editTextNumMsg = (EditText) findViewById(R.id.editTextNumMsgPerSec);
			client = new Client(clientLogsTextView, sensorsManager,
					Integer.parseInt(editTextNumMsg.getText().toString()));
			Button button = (Button) findViewById(R.id.buttonStartStop);
			RadioButton radioButtonAcc = (RadioButton) findViewById(R.id.radioButtonAcc);
			RadioButton radioButtonGyr = (RadioButton) findViewById(R.id.radioActivateGyro);
			EditText editTextIP = (EditText) findViewById(R.id.editTextIPServer);
			ConnectTask connectTast = new ConnectTask();
			DisconnectTask disconnectTask = new DisconnectTask();
			if (!started) {
				started = true;
				button.setText("Stop");
				if (radioButtonAcc.isChecked()) {
					// Log.i("Hi", "Hi");
					ListenSensorsTask listenSensorsTask = new ListenSensorsTask();
					listenSensorsTask.execute(1);
				} else if (radioButtonGyr.isChecked()) {
					ListenSensorsTask listenSensorsTask = new ListenSensorsTask();
					listenSensorsTask.execute(0);
				} else {
					// will start sending Wifi packets
					connectTast
							.execute(editTextIP.getText().toString(), "1224");
				}
			} else {
				started = false;
				button.setText("Start");
				if (radioButtonAcc.isChecked() || radioButtonGyr.isChecked()) {
					sensorsManager.stopListening();
				} else {
					// will stop sending Wifi packets
					disconnectTask.execute((Void) null);
				}
			}
		}
	}
}